<template>
  <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: 'homepage' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片 -->
  <el-card>
    <el-button type="primary" @click="dialogAdd = true">添加角色</el-button>
    <!-- 表格渲染  -->
    <el-table :data="roleslist" style="width: 100%;margin-top: 15px;" v-if="roleslist" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template #default="scope">
          <el-row class="row" :class="['dbbottom', index === 0 ? 'dbtop' : '', 'vcenter']"
            v-for="(item, index) in scope.row.children" :key="item.id">
            <!-- 渲染一级 -->
            <el-col :span="5">
              <el-tag closable @close="removeById(scope.row, item.id)">{{ item.authName }}</el-tag>
              <el-icon>
                <CaretRight />
              </el-icon>
            </el-col>
            <!-- 渲染二级和三级 -->
            <el-col :span="19">
              <el-row :class="[index1 === 0 ? '' : 'dbtop', 'vcenter']" v-for="(item1, index1) in item.children"
                :key="item1.id">
                <!-- 渲染二级 -->
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                  <el-icon>
                    <CaretRight />
                  </el-icon>
                </el-col>
                <!-- 渲染三级 -->
                <el-col :span="18">
                  <el-tag type="warning" v-for="(item2, index2) in item1.children" :key="item2.id" closable
                    @close="removeById(scope.row, item2.id)">
                    {{ item2.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#"/>
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="roleDesc" label="角色描述" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" icon="edit" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" icon="delete" @click="roleDelete(scope.row.id)">删除</el-button>
          <el-button size="small" type="warning" icon="setting" @click="showSetRinght(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 添加角色对话框 -->
  <el-dialog v-model="dialogAdd" title="添加角色信息" width="450" @close="addDialogClose()">
    <el-form :model="role" :rules="addFormRules" ref="roleRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="role.roleName" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="role.roleDesc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAdd = false">取消</el-button>
        <el-button type="primary" @click="addroles()">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 编辑角色对话框 -->
  <el-dialog v-model="editDialog" title="修改角色信息" width="450" @close="addroleClose()">
    <el-form :model="rolesfrom" :rules="addFormRules" ref="roleRefto">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="rolesfrom.roleName" disabled />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="rolesfrom.roleDesc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="addrole_two()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 分配权限对话框 -->
  <el-dialog v-model="quanxian" title="分配权限" width="450" @close="setRightClose()">
    <!-- 树形控件 -->
    <el-tree :data="rightslist" :props="rightlistProps" show-checkbox node-key="id" default-expand-all
      :default-checked-keys="defkeys" ref="treeRef"/>
    <template #footer="scope">
      <div class="dialog-footer">
        <el-button @click="quanxian = false">取 消</el-button>
        <el-button type="primary" @click="RoleConfirm()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { ElMessage } from 'element-plus';
export default {
  data() {
    return {
      roleslist: [],
      dialogAdd: false,      //控制添加角色对话框
      editDialog: false,    //控制编辑角色对话框
      quanxian: false,   //控制权限对话框
      rolesfrom: {},    //角色查询存储的数据
      rightslist: [],    //所有权限的数据
      rightlistProps: {      //树形控件
        children: 'children',   //数组中
        label: 'authName'    //显示的字段
      },
      defkeys: [],     //默认选中的节点id的数据
      roleID:'',     //即将分配权限的角色ID
      role: {
        roleName: "",
        roleDesc: "",
      },
      //校验规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    //获取角色角色数据
    async getroleslist() {
      const res = await this.$axios.get("roles")
      this.roleslist = res.data.data
      // console.log(this.roleslist);
    },
    //添加提交角色
    addroles() {
      this.$refs.roleRef.validate(async valid => {    //验证表单通过才能提交
        if (!valid) return
        const res = await this.$axios.post("roles", this.role)
        console.log(res);
        if (res.data.meta.status == 201) {
          ElMessage({
            message: "创建成功",
            type: 'success',
          })
          this.getroleslist();
          this.dialogAdd = false
        } else {
          ElMessage.error("创建失败" + res.data.meta.msg)
        }
      })
    },
    //修改编辑角色
    async handleEdit(id) {
      // console.log(id);
      this.editDialog = true;
      const res = await this.$axios.get("roles/" + id)
      if (res.data.meta.status == 200) {
        ElMessage({
          message: "获取成功",
          type: 'success'
        })
        this.rolesfrom = res.data.data
        // console.log(this.rolesfrom);
      } else {
        ElMessage.error(res.data.meta.msg)
      }
    },
    //编辑角色提交
    addrole_two() {
      this.$refs.roleRefto.validate(async valid => {     //验证表单通过才提交
        if (!valid) return
        const res = await this.$axios.put("roles/" + this.rolesfrom.roleId, {
          roleName: this.rolesfrom.roleName,
          roleDesc: this.rolesfrom.roleDesc
        })
        if (res.data.meta.status == 200) {
          ElMessage({
            message: "更新成功",
            type: 'success'
          })
          this.editDialog = false;   //关闭对话框
          this.getroleslist()    //刷新数据列表
        } else {
          ElMessage.error(res.data.meta.msg)
        }
      })
    },
    //根据ID删除用户
    async roleDelete(id) {
      try {
        await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await this.$axios.delete("roles/" + id);
        console.log(res);
        if (res.data.meta.status == 200) {
          this.getroleslist();
          this.$message({
            message: "删除成功",
            type: 'success'
          })
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          this.$message.error('删除失败')
        }
      }
    },
    //清空添加角色对话框内容
    addDialogClose() {
      this.$refs.roleRef.resetFields()
    },
    //清空编辑角色对话框内容
    addroleClose() {
      this.$refs.roleRefto.resetFields()
    },
    //根据id删除对应的权限
    async removeById(role, rightid) {
      //弹框确认删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const res = await this.$axios.delete(`roles/${role.id}/rights/${rightid}`)
      // console.log(res);
      if (res.data.meta.status == 200) {
        ElMessage({
          message: "取消权限成功",
          type: 'success'
        })
        // console.log(res);
        // this.getroleslist()
        role.children = res.data.data
      } else {
        ElMessage.error(res.data.meta.msg)
      }

    },
    //展示权限对话框
    async showSetRinght(role) {
      this.roleID = role.id;
      const res = await this.$axios.get("rights/tree")
      if (res.data.meta.status == 200) {
        ElMessage({
          message: "获取权限列表成功",
          type: 'success'
        })
        // console.log(res);
        this.rightslist = res.data.data
        // console.log(this.rightslist);
        this.getLeafkeys(role, this.defkeys)      //递归获取三级节点的ID
      } else {
        ElMessage.error(res.data.meta.msg)
      }
      this.quanxian = true;    //权限对话框显示

    },
    //采用递归方法获取三级节点的ID
    getLeafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafkeys(item, arr)
      )
    },
    setRightClose() {    //监听权限对话框的关闭事件
      this.defkeys = []
    },
    //权限对话框确认
    async RoleConfirm() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),   //通过 keys 设置目前勾选的节点
        ...this.$refs.treeRef.getHalfCheckedNodes(),   //返回目前半选中的节点所组成的数组
      ]
      // console.log(keys);
      const idStr = keys.join(",")  //以逗号分割

      const res = await this.$axios.post(`roles/${this.roleID}/rights`, { rids: idStr })
      if (res.data.meta.status==200) {
        ElMessage({
          message: "更新成功",
          type:'success'
        })
        this.getroleslist()
        this.quanxian = false;
      } else {
        ElMessage.error(res.data.meta.msg)
      }
    }

  },
  mounted() {        //挂载之后调用
    this.getroleslist()
  }
}
</script>
<style scoped>
.row {
  margin-top: 10px;
  margin-left: 55px;
}

.el-tag {
  margin: 8px;
}

.dbtop {
  border-top: 1px solid #eee;
}

.dbbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>